#ifndef __M_FMT_H__
#define __M_FMT_H__

#include <iostream>

#include "message.hpp"
#include "level.hpp"
#include <vector>
#include <string>
#include <cassert>
#include <sstream>

namespace bin
{
    // 抽象格式化子项基类
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual void format(std::ostream &out, LogMsg &msg) = 0;
    };
    // 派生格式化子项子类
    class MsgFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._payload;
        }
    };

    class LevelFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << LogLevel::toString(msg._level);
        }
    };

    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(const std::string &fmt = "%H:%M:%S")
            : _time_fmt(fmt)
        {
        }
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            struct tm t;
            localtime_r(&msg._ctime, &t);
            char tmp[32] = {0};
            strftime(tmp, 31, _time_fmt.c_str(), &t);
            out << tmp;
        }

    private:
        std::string _time_fmt;
    };

    class FileFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._file;
        }
    };

    class LineFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._line;
        }
    };

    class ThreadFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._id;
        }
    };

    class LoggerFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << msg._logger;
        }
    };

    class TabFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << "\t";
        }
    };

    class NLineFormatItem : public FormatItem
    {
    public:
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << "\n";
        }
    };

    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(const std::string &str)
            : _str(str)
        {
        }
        virtual void format(std::ostream &out, LogMsg &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%c][%f][%l][%p]%T%m%n")
            : _pattern(pattern)
        {
            assert(parsePattern());
        }

        std::string format(LogMsg &msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }

        void format(std::ostream &out, LogMsg &msg)
        {
            for (auto &item : _items)
            {
                item->format(out, msg);
            }
        }
    private:
        
        bool parsePattern()
        {
            std::string key;
            std::string val;

            for (int i = 0; i < _pattern.size();)
            {
    
                if (_pattern[i] != '%')
                {
                    val += _pattern[i];
                    i++;
                    continue;
                }
                // 如果是两个%连起来，就是固定格式%
                else if (i + 1 < _pattern.size() && _pattern[i + 1] == '%')
                {
                    val += '%';
                    i += 2;
                    continue;
                }

                if (!val.empty())
                {
                    _items.push_back(createItem("", val));
                    val.clear();
                }

                // 走到这里，说明是%后面的格式字符
                i++;
                if(i == _pattern.size())
                {
                    std::cerr << "%之后没有格式化字符\n";
                    return false;
                }
                key += _pattern[i];
                i++;
                if (i < _pattern.size() && _pattern[i] == '{')
                {
                    i++;
                    while (i < _pattern.size() && _pattern[i] != '}')
                        val += _pattern[i++];

                    // 走到末尾跳出循环，都没有遇到}，直接出错
                    if (i == _pattern.size())
                    {
                        std::cerr << "子规则{}匹配出错" << std::endl;
                        return false;
                    }
                    i++; // i指向}位置，走一步到新位置
                }
                _items.push_back(createItem(key, val));

                key.clear();
                val.clear();
            }
            return true;
        }

        FormatItem::ptr createItem(const std::string &key, const std::string &val)
        {
            if (key == "d")
                return std::make_shared<TimeFormatItem>(val);
            if (key == "t")
                return std::make_shared<ThreadFormatItem>();
            if (key == "c")
                return std::make_shared<LoggerFormatItem>();
            if (key == "f")
                return std::make_shared<FileFormatItem>();
            if (key == "l")
                return std::make_shared<LineFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "T")
                return std::make_shared<TabFormatItem>();
            if (key == "m")
                return std::make_shared<MsgFormatItem>();
            if (key == "n")
                return std::make_shared<NLineFormatItem>();
            if (key == "")
                return std::make_shared<OtherFormatItem>(val);
            
            std::cerr << "没有对应的格式化字符：%" << key << std::endl;
            exit(1);
        }

    private:
        std::string _pattern;
        std::vector<FormatItem::ptr> _items;
    };
}

#endif